package main

import (
	"fmt"
	"gino/boot"
	"gino/global"
	"gino/router"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {

	// 路由初始化
	r := router.InitRouter()

	// 设置Gin模式
	gin.SetMode(global.Config.App.RunMode)

	// API SERVER
	srv := &http.Server{
		Addr:           global.Config.App.Addr,
		Handler:        r.GinEngine,
		ReadTimeout:    global.Config.App.ReadTimeout * time.Second,
		WriteTimeout:   global.Config.App.WriteTimeout * time.Second,
		MaxHeaderBytes: 1 << 20, // 1 MB
	}
	log.Printf("server start on %s", global.Config.App.Addr)

	go func() {
		if err := srv.ListenAndServe(); err != nil {
			panic(fmt.Sprintf("listen error: %s\n", err))
		}
	}()

	// 分布式cron
	redisLock, ok := boot.AcquireCron()
	if ok {
		defer redisLock.Release()
	}

	// 等待 syscall.SIGINT syscall.SIGTERM 优雅地关闭服务器
	// 超时 5秒
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutdown Server ...")

	//ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	//log.Printf("%+v", ctx)
	//defer cancel()
	//if err := srv.Shutdown(ctx); err != nil {
	//	panic(fmt.Sprintf("Server Shutdown: %s\n", err))
	//}
	//log.Println("Server exiting")

	// 程序结束前关闭Redis链接
	defer global.Redis.Close()

}
